﻿using System;
using System.Configuration;
using System.Linq;
using NDatabase;
using PagedList;

namespace Mini.Data
{
    public class Reponsitory<T> : IReponsitory<T> where T : class
    {
        private readonly string _folderLog = string.Format("{0}.db", ConfigurationSettings.AppSettings["Folder"]);

        public void AddOrUpdate(T t)
        {
           using (var odb = OdbFactory.Open(_folderLog))
            {
                odb.Store(t);
            }
        }

        public void Delete(T t)
        {
            using (var odb = OdbFactory.Open(_folderLog))
            {
                odb.Delete(t);
            }
        }

        public void DeleteAllData()
        {
            using (var odb = OdbFactory.Open(_folderLog))
            {
                var data = odb.Query<T>().Execute<T>().ToList();
                if (data.Any())
                {
                    foreach (var item in data)
                    {
                        odb.Delete(item);
                    }
                }
               
            }
        }

        public IPagedList<T> GetList(int pageIndex, int pageSize, Func<IQueryable<T>, IOrderedQueryable<T>> orderbyFunc = null)
        {
            using (var odb = OdbFactory.Open(_folderLog))
            {
                pageIndex = pageIndex <= 0 ? 1 : pageIndex;
                pageSize = pageSize <= 0 ? 10 : pageSize;
                IQueryable<T> iQueryable = odb.AsQueryable<T>();
                if (orderbyFunc != null)
                   iQueryable = orderbyFunc(iQueryable);

                return iQueryable.ToPagedList(pageIndex, pageSize);
            }
        }

        public T Get(Func<T, bool> where = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderbyFunc = null)
        {
            using (var odb = OdbFactory.Open(_folderLog))
            {
                IQueryable<T> iQueryable = odb.AsQueryable<T>();
                if (orderbyFunc != null)
                    iQueryable = orderbyFunc(iQueryable);
                if (where != null)
                    iQueryable = iQueryable.Where(where).AsQueryable();
                return iQueryable.FirstOrDefault();
            }
        }
    }
}
